package com.scedu.dao;

import com.scedu.domain.Student;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/*
Studentdao接口的springtemplateJDBC实现类
 */
public class StudentDAOSPRINGJDBCImpl implements StudentDAO{


    private JdbcTemplate jdbcTemplate;
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public List<Student> query() {
        final List<Student> students=new ArrayList<Student>();
        String sql="select * from tb_student";
        jdbcTemplate.query(sql, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet resultSet) throws SQLException {

                    int id=resultSet.getInt("id");
                    String name=resultSet.getString("name");
                    Integer age=resultSet.getInt("age");

                    Student student=new Student();
                    student.setAge(age);
                    student.setId(id);
                    student.setName(name);
                    students.add(student);

                    System.out.println(student);

            }
        });
        return students;
    }

    @Override
    public void add(Student student) {
        String name=student.getName();
        Integer age=student.getAge();
        String sql="insert  into tb_student (name,age) value (?,?)";
        jdbcTemplate.update(sql,new Object[]{student.getName(),student.getAge()});

    }
}
